package com.gmako.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gmako.entity.Adress;
import com.gmako.entity.Userinfo;
import com.gmako.service.AddressService;
import com.gmako.service.RegisterService;
import com.gmako.utils.MD5;
import com.gmako.utils.MailManagers;
import com.gmako.utils.ResponseUtils;
import com.gmako.utils.StaticVariables;

@Controller
@RequestMapping("/userRegister.do")
public class UserRegisterController extends BaseController{
	@Autowired(required=false) 
	private RegisterService  registerService;
	@Autowired(required=false) 
	private AddressService addressService;
	@Autowired(required=false) 
	private MailManagers mailmanager;
	/**显示注册页面**/
	@RequestMapping(params = "method=viewRegister")
	public ModelAndView viewRegister(HttpServletRequest request,HttpServletResponse response){
		String recomendUserId_tr = request.getParameter("recomendUserId");
		int recomendUserId = Integer.parseInt(recomendUserId_tr.toString());
		//把recomendUserId放到session中
		request.getSession().setAttribute(StaticVariables.COMMEND_USERID,recomendUserId);
		List list = addressService.findByProperty(Adress.class,
				"pid", 0);
		request.setAttribute("flist", list);
		Adress ha = (Adress) list.get(0);
		List zlist = addressService.findByProperty(Adress.class,
				"pid", ha.getId());
		request.setAttribute("zlist", zlist);
		return new ModelAndView("UserRegister", "list", list);
	}
	
	/**
	 * 用户注册
	 * 
	 * @author yezhenchi
	 * @param request
	 * @param response
	 * @param users
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=register")
	public String personalReg(HttpServletRequest request,
			HttpServletResponse response, Userinfo userInfo_p) throws Exception {
		HttpSession session = request.getSession();
		int recomendUserId =Integer.parseInt(session.getAttribute(StaticVariables.COMMEND_USERID).toString());
		//数据库中查询是否存在该用户
		int tag = registerService.findUidIs(recomendUserId);
		if(tag==0){
			userInfo_p.setCommend(0);
		}else if(tag==1){
			userInfo_p.setCommend(recomendUserId);
			
		}
		//MD5
		userInfo_p.setPwd(new MD5().getMD5(userInfo_p.getPwd()));
//		// 执行注册
		registerService.save(userInfo_p);
		return null;
	}
	
	
	/**
	 * 获得城市
	 * 
	 * @author yezhenchi
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(params = "method=getzList")
	public @ResponseBody
	String getzList(@RequestParam("aid") String aid,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		List<Adress> list = addressService.findByProperty(Adress.class,
				"pid", Integer.parseInt(aid));
		JSONArray jsonArray = JSONArray.fromObject(list);
		response.getWriter().print(jsonArray.toString());
		return null;
	}
	/**
	 * 查询用户是否注册
	 * 
	 * @author yezhenchi
	 * @param request
	 * @param response
	 * @param users
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=findNameIs")
	public void findNameIs(HttpServletRequest request,
			HttpServletResponse response,Userinfo user) throws Exception {
		String name2 = request.getQueryString();
		String name = URLDecoder.decode(request.getParameter("username").toString(), "utf-8");
		int tag = registerService.findNameIs(name);
		if(tag==1){
			ResponseUtils.renderText(response, "1");
		}
		else{
			ResponseUtils.renderText(response, "0");
		}
	}
//	
	/**
	 * 查询邮箱是否注册
	 * 
	 * @author yezhenchi
	 * @param request
	 * @param response
	 * @param users
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=findEmailIs")
	public void findEmailIs(HttpServletRequest request,
			HttpServletResponse response,Userinfo user) throws Exception {
		String email = URLDecoder.decode(request.getParameter("useremail").toString(), "utf-8");
		int tag = registerService.findEmailIs(email);
		if(tag==1){
			ResponseUtils.renderText(response, "1");
		}
		else{
			ResponseUtils.renderText(response, "0");
		}
	}
	
	private int width = 66;
	private int height = 20;
	private int codeCount = 4;
	private int xx = 0;
	private int fontHeight;
	private int codeY;
	char[] codeSequence = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };

	
	/**
	 * 验证码
	 * 
	 * @author yezhenchi
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "method=yanzheng")
	public void captcha(HttpServletRequest request, HttpServletResponse response) {
		//System.out.println("验证码");
		xx = width / codeCount;
		fontHeight = height - 2;
		codeY = height - 4;
		BufferedImage buffImg = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D gd = buffImg.createGraphics();
		Random random = new Random();
		gd.setColor(Color.white);
		gd.fillRect(0, 0, width, height);
		Font font = new Font("Fixedsys", Font.PLAIN, fontHeight);
		gd.setFont(font);
		gd.setColor(Color.BLACK);
		gd.drawRect(0, 0, width - 1, height - 1);
		gd.setColor(Color.BLACK);
		for (int i = 0; i < 5; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			gd.drawLine(x, y, x + xl, y + yl);
		}
		StringBuffer randomCode = new StringBuffer();
		// int red = 255, green = 255, blue = 255;
		for (int i = 0; i < codeCount; i++) {
			String strRand = String.valueOf(codeSequence[random.nextInt(10)]);
			// red = random.nextInt(255);
			// green = random.nextInt(255);
			// blue = random.nextInt(255);
			gd.setColor(new Color(1, 1, 1));
			gd.drawString(strRand, i * xx, codeY);
			randomCode.append(strRand);
		}
		HttpSession session = request.getSession();
		session.setAttribute("validateCode", randomCode.toString());
		//System.out.println(randomCode.toString());
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream sos = null;
		try {
			sos = response.getOutputStream();
			ImageIO.write(buffImg, "jpeg", sos);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				sos.flush();
				sos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}


	/**
	 * 获取当前验证码
	 * 
	 * @author yezhenchi
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "method=getyanzheng")
	public void getCurrentCaptcha(HttpServletRequest request,
			HttpServletResponse response) {
		String validateCode = (String) request.getSession().getAttribute(
				"validateCode");
		ResponseUtils.renderText(response, validateCode);
	}
}
